package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.fengin.CouponSpuBoundsService;
import com.atguigu.gulimall.product.fengin.SearchFeignService;
import com.atguigu.gulimall.product.fengin.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.SkuHasStockVo;
import com.atguigu.gulimall.product.vo.product.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;


/**
 * @author ShiJieLin
 */
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService descService;
    @Resource
    private SkuImagesService imagesService;
    @Resource
    private AttrService attrService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private CouponSpuBoundsService couponSpuBoundsService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * TODO　事务后期完善，分布式事务
     *
     * @param vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuSaveVo vo) {

        //　1．保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfo);
        this.save(spuInfo);

        //　2．保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfo.getId());
        descEntity.setDecript(String.join(",", decript));
        descService.saveSpuInfoDesc(descEntity);

        //　3．保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(spuInfo.getId(), images);

        //　4．保存spu的规格参数; pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            // 4.1 使用ID查询出对应的规格参数
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());

            productAttrValue.setAttrName(attrEntity.getAttrName());
            productAttrValue.setAttrId(attr.getAttrId());
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setQuickShow(attr.getShowDesc());
            productAttrValue.setSpuId(spuInfo.getId());
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntities);

        //　５．保存spu的积分信息；gulimall_sms -> sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSpuId(spuInfo.getId());
        spuBoundTo.setGrowBounds(bounds.getGrowBounds());
        spuBoundTo.setBuyBounds(bounds.getBuyBounds());
        // 5.1 远程调用 gulimall-coupon中的SpuBoundsController.save()
        R resultBounds = couponSpuBoundsService.save(spuBoundTo);
        if (resultBounds.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //　６．保存当前spu对应的所有sku信息；
        List<Skus> skus = vo.getSkus();
        if (null != skus && skus.size() > 0) {
            skus.forEach(sku -> {
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                // 6.1. sku的基本信息；pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfo.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //　６.2 sku的图片信息；pms_sku_image
                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // 剔除URL为空的图片 返回true就是需要，false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                imagesService.saveBatch(imagesEntities);

                //　６.3 sku的销售属性信息：pms_sku_sale_attr_value
                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                /** ６.4 sku的优惠、满减等信息；gulimall_sms -> sms_sku_ladder
                 *   sms_sku_full_reduction  sms_member_price
                 */
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R resultSkuFullReduction = couponSpuBoundsService.saveSkuReduction(skuReductionTo);
                    if (resultSkuFullReduction.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 1.根据SpuId查询 sku(销售属性)的信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        // 2.查询当前spuId 所有的规格参数
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrlistforspu(spuId);
        // 2.1获取规格参数id
        List<Long> attrIds = productAttrValueEntities.stream()
                .map(item -> item.getAttrId()).collect(Collectors.toList());
        // 2.2根据所有的规格参数ID 筛选出可被检索的规格参数
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        // 2.3转化为Set集合
        Set<Long> searchAttrIdsSet = searchAttrIds.stream().collect(Collectors.toSet());
        // 2.4从所有的规格参数中过滤出 可以被检索的规格参数，然后封装到 SkuEsModel.Attrs
        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter((itme) -> {
            return searchAttrIdsSet.contains(itme.getAttrId());
        }).map((item) -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        // 3.远程调用库存系统，查看当前的商品的库存
        // 3.1获取skuId
        List<Long> skuIds = skuInfoEntities.stream().map((skuInfoEntity) -> {
            return skuInfoEntity.getSkuId();
        }).collect(Collectors.toList());
        // 3.2远程调用库存系统，根据skuIds获取当前商品是否有库存
        R hasStock = wareFeignService.getSkuHasStock(skuIds);
        List<SkuHasStockVo> skuHasStock =  hasStock.getData(new TypeReference<List<SkuHasStockVo>>(){});

        Map<Long, Boolean> stockMap = null;
        try {
            // 3.3将是否有库存转化为map对象
            stockMap = skuHasStock.stream().collect(
                    // key 的函数 skuId当key
                    Collectors.toMap((SkuHasStockVo) -> SkuHasStockVo.getSkuId(),
                            // value的函数 是否有库春当value
                            SkuHasStockVo -> SkuHasStockVo.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
        }
        Map<Long, Boolean> finalStockMap = stockMap;
        // 4.将数据分装到SkuEsModel中
        List<SkuEsModel> esModelList = skuInfoEntities.stream().map((skuInfoEntity) -> {

            SkuEsModel skuEsModel = new SkuEsModel();

            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            // TODO 热度评分 关于商品的排序情况
            skuEsModel.setHotScore(0L);
            // TODO 库存
            if(null != finalStockMap){
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }else {
                skuEsModel.setHasStock(true);
            }
            // 查询品牌信息封装
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandId(brandEntity.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            // 查询分类信息封装
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalogId(categoryEntity.getCatId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            // 封装可检索的 规格参数
            skuEsModel.setAttrs(attrsList);
            // 封装其他规格参数名一样的 规格参数
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            return skuEsModel;
        }).collect(Collectors.toList());

        // 远程调用ES服务保存相关的信息
        R r = searchFeignService.productStatusUp(esModelList);

        if (r.getCode() == 0) {
            //远程调用成功
            //TODO 6、修改当前spu的状态
            this.baseMapper.updaSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            //TODO 7、重复调用？接口幂等性:重试机制
        }
    }

    @Override
    public SpuInfoEntity querySpuInfoBySkuId(Long skuId) {

        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);

        Long spuId = skuInfo.getSpuId();

        SpuInfoEntity spuInfo = baseMapper.selectById(spuId);

        BrandEntity brandEntity = brandService.getById(spuInfo.getBrandId());

        spuInfo.setBrandName(brandEntity.getName());

        return spuInfo;
    }
}